#include <iostream>
#include <vector>
#include <ctime>
#include <windows.h>

#define MAX_SIZE 100

using namespace std;

bool is_size_ok(int);
const vector<int> *fibon_seq(int);
bool fibon_elem(int, long long &);

int main()
{
    int pos;
    char cmd;
    long long elem;
    
    do
    {
        cout << "Please enter a position: ";
        cin >> pos;
        clock_t time_start = clock();
        Sleep(1);

        if (fibon_elem(pos, elem))
        {
            clock_t time_end = clock();
            cout << "elemnt # " << pos
                 << " is " << elem << endl
                 << "Time use is "
                 << 1000 * (time_end - time_start) / (double)CLOCKS_PER_SEC
                 << "ms" << endl;
        }
        else
            cout << "Sorry. Could not calculate # "
                 << pos << endl;

        cout << "Try again ? (Y/N)"<< endl;
        cin >> cmd;

    } while (cmd == 'Y' || cmd == 'y');

    cout << "See You !";

    return 0;
}


inline bool is_size_ok(int size)
{
    if (size <= 0 || size > MAX_SIZE)
    {
        cerr << "Oops: requested size is not supported: "
             << size << " -- can't fulfill request.\n";
        return false;
    }
    return true;
}

const vector<int>* fibon_seq(int size)
{
    static vector<int> elems;

    if (!is_size_ok(size))
        return 0;
    for (int ix = elems.size(); ix < size; ix++)
    {
        if (ix == 0 || ix == 1)
            elems.push_back(1);
        else
            elems.push_back(elems[ix - 1] + elems[ix - 2]);
    }
    return &elems;
}

inline bool fibon_elem(int pos, long long &elem)
{
    const vector<int> *pseq = fibon_seq(pos);

    if (!pseq)
        {
            elem = 0;
            return false;
        }
    elem = (*pseq)[pos - 1];
    return true;
}

